package org.chnxi.study.springcloud.dubbo.dto;

import lombok.*;

import java.util.UUID;

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class TransactionDescrib {

    private String globalTransId; //全局交易流水
    //private String preReqTransId; //当前交易中的流水，如果当前交易的请求对象中为null，需使用globalTransId
    private String curReqTransId;  //本次请求流水
    private String curRespTransId;  //本次响应流水

    /**
     * 创建一个新的交易头描述信息
     * @return
     */
    public static TransactionDescrib newInstance4Request(){
        TransactionDescrib td = new TransactionDescrib();
        td.setGlobalTransId(UUID.randomUUID().toString().replace("-",""));
        td.setCurReqTransId(UUID.randomUUID().toString().replace("-",""));
        return td;
    }

    /**
     * 在请求内创建下一次请求对象，主要用于保留链路信息
     * @param curTransDesc
     * @return
     */
    public static TransactionDescrib newTnstance4Request(TransactionDescrib curTransDesc){
        TransactionDescrib td = new TransactionDescrib();
        if(curTransDesc == null){
            td.setGlobalTransId(UUID.randomUUID().toString().replace("-",""));
        }else{
            td.setGlobalTransId(curTransDesc.globalTransId);
        }
        //td.setPreReqTransId(curTransDesc.getCurReqTransId() == null ? curTransDesc.globalTransId : curTransDesc.getCurReqTransId());
        td.setCurReqTransId(UUID.randomUUID().toString().replace("-",""));
        return td;
    }

    /**
     * 根据请求创建响应对象
     * @param reqTransDesc
     * @return
     */
    public static TransactionDescrib newInstance4Response(TransactionDescrib reqTransDesc){
        TransactionDescrib td = new TransactionDescrib();
        td.setCurRespTransId(UUID.randomUUID().toString().replace("-",""));
        if(reqTransDesc == null){
            td.setGlobalTransId(UUID.randomUUID().toString().replace("-",""));
            td.setCurReqTransId("NULL");
        }else{
            td.setGlobalTransId(reqTransDesc.getGlobalTransId());
            td.setCurReqTransId(reqTransDesc.getCurReqTransId());
        }
        return td;
    }

}
